//
//  SigninAddressMapViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/12/12.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "SigninAddressMapViewController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import<BaiduMapAPI_Map/BMKMapView.h>
#import<BaiduMapAPI_Location/BMKLocationService.h>
#import<BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import <BaiduMapAPI_Search/BMKSuggestionSearch.h>
#import<BaiduMapAPI_Search/BMKSuggestionSearchOption.h>
#import <BaiduMapAPI_Map/BMKPinAnnotationView.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Map/BMKCircle.h>
#import <BaiduMapAPI_Map/BMKPolygon.h>
#import <BaiduMapAPI_Map/BMKCircleView.h>
#import <BaiduMapAPI_Map/BMKGroundOverlay.h>

@interface SigninAddressMapViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
{
    BMKMapView *_mapView;  //地图
    BMKLocationService *_locService;  //定位
    BMKGeoCodeSearch *_geocodesearch; //地理编码主类，用来查询、返回结果信息
    UITapGestureRecognizer *_tapGesture;//手势
    BMKSuggestionSearch *_suggestionSearch;
    UIView *_alphaView;//黑色背景框
    BMKPinAnnotationView *newAnnotation;
    BMKGroundOverlay* ground2;
    BMKPointAnnotation* nowAnnotation;
    BMKPointAnnotation* readyAnnotation;
}
@property (nonatomic,strong) NSString *placeX;//纬度
@property (nonatomic,strong) NSString *placeY;//经度
@end

@implementation SigninAddressMapViewController


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=YES;
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    CLLocationCoordinate2D coordinate=CLLocationCoordinate2DMake([self.addressX doubleValue], [self.addressY doubleValue]);
    readyAnnotation= [[BMKPointAnnotation alloc]init];
    readyAnnotation.coordinate = coordinate;
    readyAnnotation.title = self.addressStr;
    [_mapView addAnnotation:readyAnnotation];

//    // 添加圆形覆盖物
//    CLLocationCoordinate2D coor3;
//    coor3.latitude = [self.placeX doubleValue];
//    coor3.longitude = [self.placeY doubleValue];
//    BMKCircle* circle = [BMKCircle circleWithCenterCoordinate:coor3 radius:500];
//    
//    [_mapView addOverlay:circle];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    self.navigationController.navigationBar.hidden=NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!_mapView) {
        [self creatView];
    }
    // Do any additional setup after loading the view.
}

- (void)creatView{
    //添加地图视图
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    _mapView.showsUserLocation = NO; //是否显示定位图层（即我的位置的小圆点）
    _mapView.zoomLevel = 18;//地图显示比例
    _mapView.mapType = BMKMapTypeStandard;//设置地图为空白类型
    _mapView.showMapScaleBar = YES;
    //自定义比例尺的位置
    _mapView.mapScaleBarPosition = CGPointMake(_mapView.frame.size.width - 70, _mapView.frame.size.height - 68);
    [self.view addSubview:_mapView];
    
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    
    _geocodesearch.delegate = self;
    [self startLocation];
    
//    //地理反编码
//    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
//    reverseGeocodeSearchOption.reverseGeoPoint = coor;
//    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
//    if(flag){
//        NSLog(@"反geo检索发送成功");
//        [_locService stopUserLocationService];
//    }else{
//        NSLog(@"反geo检索发送失败");
//    }
    
    //返回按钮
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(10, 20, 40, 40)];
    backView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:backView];
    
    UIView *alphoView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, backView.width, backView.height)];
    alphoView.alpha=0.4;
    alphoView.backgroundColor=[UIColor blackColor];
    [backView addSubview:alphoView];
    
    UIButton *backButton=[UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame=CGRectMake(0, 0, backView.width, backView.height);
    [backButton setImage:[UIImage imageNamed:@"icon1_1@2x"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:backButton];
    
    //    if (_searchView) {
    //        //防止搜索按钮多次被点击
    //        return;
    //    }
    //    _grayButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 64, IPHONE_WIDTH, IPHONE_HEIGHT-64)];
    //    [_grayButton setBackgroundColor:COLOR(106, 107, 108, 0.7)];
    //    [_grayButton addTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:_grayButton];

}

//根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if (annotation==readyAnnotation) {
        NSString *AnnotationViewID = @"annotation";
        //根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
        BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
            ((BMKPinAnnotationView*)annotationView).animatesDrop = NO;
            annotationView.image=[UIImage imageNamed:@"k_current@2x"];
        }
        
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        annotationView.annotation = annotation;
        annotationView.canShowCallout = YES;
        //添加文字说明
        UIView *backView=[[UIView alloc]initWithFrame:CGRectMake((100-annotationView.center.x)/2, annotationView.height, 100, 20)];
        backView.center=CGPointMake(annotationView.center.x+5, annotationView.height+10);
        backView.backgroundColor=[UIColor clearColor];
        [annotationView addSubview:backView];
        
        UIView *alphoView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, backView.width, backView.height)];
        alphoView.alpha=0.5;
        alphoView.backgroundColor=[UIColor yellowColor];
        [backView addSubview:alphoView];
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, backView.width, backView.height)];
        label.textColor=[UIColor purpleColor];
        label.font=FONT_13;
        label.textAlignment=NSTextAlignmentCenter;
        label.text=@"员工考勤地点";
        [backView addSubview:label];
        return annotationView;
    }
    NSString *AnnotationViewID = @"annotationViewID";
    //根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
    BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        ((BMKPinAnnotationView*)annotationView).animatesDrop = NO;
        annotationView.image=[UIImage imageNamed:@"icon_mark@2x"];
    }
    
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    annotationView.canShowCallout = YES;
    [self addTextInView:annotationView text:@"我的位置" backgroundColor:[UIColor blackColor] textColor:[UIColor blackColor]];
    return annotationView;
}

#pragma mark -气泡文字提示
- (void)addTextInView:(BMKAnnotationView *)annotationView text:(NSString *)text backgroundColor:(UIColor *)backgroundColor textColor:(UIColor *)textColor{
    //添加文字说明
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake((60-annotationView.center.x)/2, annotationView.height, 60, 20)];
    backView.center=CGPointMake(annotationView.center.x+5, annotationView.height+10);
    backView.backgroundColor=[UIColor clearColor];
    [annotationView addSubview:backView];
    
    UIView *alphoView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, backView.width, backView.height)];
    alphoView.alpha=0.1;
    alphoView.backgroundColor=backgroundColor;
    [backView addSubview:alphoView];
    
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, backView.width, backView.height)];
    label.backgroundColor=[UIColor clearColor];
    label.font=FONT_13;
    label.textAlignment=NSTextAlignmentCenter;
    label.text=text;
    [backView addSubview:label];
}

#pragma mark -计算最远的距离
- (double)getDistance{
    //第一个坐标
    
    CLLocation *current=[[CLLocation alloc] initWithLatitude:self.placeX.doubleValue longitude:self.placeY.doubleValue];
    
    //第二个坐标
    
    CLLocation *before=[[CLLocation alloc] initWithLatitude:self.addressX.doubleValue longitude:self.addressY.doubleValue];
    CLLocationDistance meters=[current distanceFromLocation:before];
    return meters;
}


//开始定位
-(void)startLocation
{
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    _locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    //启动LocationService
    [_locService startUserLocationService];
}

//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
   
}

- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKCircle class]]){
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.5];
        circleView.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
        circleView.lineWidth = 5.0;
        
        return circleView;
    }
    
    if ([overlay isKindOfClass:[BMKGroundOverlay class]])
    {
        BMKGroundOverlayView* groundView = [[BMKGroundOverlayView alloc] initWithOverlay:overlay];
        return groundView;
    }
    return nil;
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    self.placeX=[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude];
    self.placeY=[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude];
    //普通态
    //以下_mapView为BMKMapView对象
    [_mapView updateLocationData:userLocation]; //更新地图上的位置
    _mapView.centerCoordinate = userLocation.location.coordinate; //更新当前位置到地图中间
    //地理反编码
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag){
        NSLog(@"反geo检索发送成功");
        //计算最小经纬度和最大经纬度两点之间的距离
        int dictance = [self getDistance];
        //这个数组就是百度地图比例尺对应的物理距离，其中2000000对应的比例是3，5对应的是21；可能有出入可以根据情况累加
        NSArray *zoomLevelArr = [[NSArray alloc]initWithObjects:@"2000000", @"1000000", @"500000", @"200000", @"100000", @"50000", @"25000", @"20000", @"10000", @"5000", @"2000", @"1000", @"500", @"200", @"100", @"50", @"20", @"10", @"5", nil];
        for (int j=0; j<zoomLevelArr.count; j++) {
            if (j + 1 < zoomLevelArr.count) {
                if (dictance < [zoomLevelArr[j] intValue] && dictance > [zoomLevelArr[j+1] intValue] ) {
                    [_mapView setZoomLevel:j+5];
                    break;
                }
            }
        }
        [_locService stopUserLocationService];
    }else{
        NSLog(@"反geo检索发送失败");
    }
}

#pragma mark -------------地理反编码的delegate---------------
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"address:%@----%@",result.addressDetail,result.address);
    _cityName=[result.addressDetail.city copy];
    _addressStr=result.address;
    nowAnnotation = [[BMKPointAnnotation alloc]init];
    nowAnnotation.coordinate = result.location;
    nowAnnotation.title = result.address;
    [_mapView addAnnotation:nowAnnotation];
    _mapView.centerCoordinate = result.location;

    //addressDetail:     层次化地址信息
    //address:    地址名称
    //businessCircle:  商圈名称
    // location:  地址坐标
    //  poiList:   地址周边POI信息，成员类型为BMKPoiInfo
}

//#pragma mark -增加气泡
//- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
//    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
//    [_mapView removeAnnotations:array];
//    array = [NSArray arrayWithArray:_mapView.overlays];
//    [_mapView removeOverlays:array];
//    if (error == BMK_SEARCH_NO_ERROR) {
//        //在此处理正常结果
//        //    //增加气泡
//        nowAnnotation = [[BMKPointAnnotation alloc]init];
//        nowAnnotation.coordinate = result.location;
//        nowAnnotation.title = result.address;
//        [_mapView addAnnotation:nowAnnotation];
//        _mapView.centerCoordinate = result.location;
//    }
//    else {
//        NSLog(@"抱歉，未找到结果");
//    }
//}

//定位失败
- (void)didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"error:%@",error);
}

//#pragma mark -searchBarDelegate
//
//- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
//    if (!_suggestionSearch) {
//        _suggestionSearch=[BMKSuggestionSearch new];
//        _suggestionSearch.delegate=self;
//    }
//    //建议列表
//    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
//    option.cityname = _cityName?_cityName:@"";
//    option.keyword  = searchBar.text;
//    BOOL flag = [_suggestionSearch suggestionSearch:option];
//    if(flag)
//    {
//        NSLog(@"建议检索发送成功");
//    }
//    else
//    {
//        NSLog(@"建议检索发送失败");
//    }
//    [self.view endEditing:YES];
//}


//- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
//    if (!_suggestionSearch) {
//        _suggestionSearch=[BMKSuggestionSearch new];
//        _suggestionSearch.delegate=self;
//    }
//    //建议列表
//    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
//    option.cityname = _cityName?_cityName:@"";
//    option.keyword  = searchBar.text;
//    BOOL flag = [_suggestionSearch suggestionSearch:option];
//    if(flag)
//    {
//        NSLog(@"建议检索发送成功");
//    }
//    else
//    {
//        NSLog(@"建议检索发送失败");
//    }
//    return YES;
//}
//
//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//    if (!_suggestionSearch) {
//        _suggestionSearch=[BMKSuggestionSearch new];
//        _suggestionSearch.delegate=self;
//    }
//    //建议列表
//    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
//    option.cityname = _cityName?_cityName:@"";
//    option.keyword  = searchBar.text;
//    BOOL flag = [_suggestionSearch suggestionSearch:option];
//    if(flag)
//    {
//        NSLog(@"建议检索发送成功");
//    }
//    else
//    {
//        NSLog(@"建议检索发送失败");
//    }
//}
//


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
